import React, { ChangeEvent } from 'react';
import { Button, Form, Input, message, Radio } from 'antd';

import { customersInfo, customersInfoPut } from 'seats/servers/servers';
import { CustomersInfo } from 'seats/schema/CheckInOut';

// 布局 详见react anti 文档
const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};
// 布局
const tailLayout = {
  wrapperCol: { offset: 8, span: 16 },
};

/**
 * IProps 传参
 */
interface IProps {
  callRecordId: string;
}

/**
 * IStates 状态
 */
interface IStates {
  /** input 列表*/
  list: CustomersInfo[];
  /** radio 用户意向--0:无意向， 1：一般意向，2：强烈意向，-1:没有收集，默认无*/
  userIntentionDegree: number;
  /** 提交状态*/
  loadingTag: boolean;
}

class UsersInfo extends React.PureComponent<IProps, IStates> {
  constructor(props: IProps) {
    super(props);
    this.state = {
      list: [],
      loadingTag: false,
      userIntentionDegree: -1,
    };
    this.onFinish = this.onFinish.bind(this);
    this.onFinishFailed = this.onFinishFailed.bind(this);
    this.inputChange = this.inputChange.bind(this);
  }

  /**
   * 客户资料-查询
   */
  async getInputListtName() {
    console.log(this.props);
    const { callRecordId } = this.props;
    if (!callRecordId) return false;
    const res = await customersInfo(callRecordId);
    if (res && res.data) {
      const { respAttributes, userIntention } = res.data;
      const list = respAttributes || [];
      this.setState({
        list: list,
        userIntentionDegree: userIntention,
      });
    }
  }

  /**
   * input输入监听
   */
  inputChange(e: ChangeEvent<HTMLInputElement>, id: string) {
    console.log(id);
  }

  /**
   * form表单提交
   */
  async onFinish(values: any) {
    console.log(values, '客户资料****提交form表单');
    this.setLoading(true);
    const { callRecordId } = this.props;
    const attributes = [];
    const { userIntentionDegree } = values;
    const keys = Object.keys(values);
    for (const item of keys) {
      if (item !== 'userIntentionDegree') {
        attributes.push({
          attributeName: item,
          attributeValue: values[item],
        });
      }
    }
    console.log('Success:', attributes, userIntentionDegree);
    try {
      await customersInfoPut(callRecordId, attributes, userIntentionDegree);
      this.setLoading(false, () => {
        message.success('客户资料保存成功');
      });
    } catch (e) {
      this.setLoading(false);
    }
  }

  /**
   * 设置请求loading tag
   */
  setLoading(tag: boolean, fn?: any) {
    setTimeout(
      () => {
        this.setState({
          loadingTag: tag,
        });
        fn && fn();
      },
      !tag ? 1000 : 0
    );
  }

  /**
   * form表单没有通过验证
   */
  onFinishFailed(errorInfo: any) {
    console.log('Failed:', errorInfo);
  }

  componentDidMount(): void {
    this.getInputListtName();
  }

  componentDidUpdate(prevProps: any): void {
    // if (prevProps.callRecordId !== this.props.callRecordId) {
    //   this.getInputListtName();
    // }
  }

  /**
   * 渲染表单列表
   */
  InitItem(list: CustomersInfo[]) {
    return list.map(item => {
      return (
        <Form.Item
          key={item.attributeId}
          label={item.attributeDesc}
          name={item.attributeName}
          initialValue={item.attributeValue}
        >
          <Input
            onChange={e => this.inputChange(e, item.attributeId)}
            readOnly={item.attributeName === 'phoneNumber'}
          />
        </Form.Item>
      );
    });
  }

  render() {
    const { loadingTag, list, userIntentionDegree } = this.state;
    console.log('userIntentionDegree回显值', userIntentionDegree);
    return (
      <div className="box-cont">
        <div className="box-tit">客户资料</div>
        <Form
          className="form-box"
          {...layout}
          name="basic"
          onFinish={this.onFinish}
          onFinishFailed={this.onFinishFailed}
        >
          {this.InitItem(list)}
          <Form.Item
            key="userIntentionDegree"
            label="用户意向"
            name="userIntentionDegree"
            initialValue={userIntentionDegree > 0 ? userIntentionDegree : 0}
          >
            <Radio.Group>
              <Radio value={0}>无意愿</Radio>
              <Radio value={1}>一般意愿</Radio>
              <Radio value={2}>强烈意愿</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item {...tailLayout}>
            <Button type="primary" loading={loadingTag} htmlType="submit">
              保存
            </Button>
          </Form.Item>
        </Form>
      </div>
    );
  }
}

export default UsersInfo;
